// @/store/firstStore.js
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { h } from "vue";
const fs = require("fs");
const path = require("path");
const Store = require("electron-store");
const { ipcRenderer } = require("electron");
const store = new Store();

const exec = require("child_process").exec;

// 定义并导出容器，第一个参数是容器id，必须唯一，用来将所有的容器
// 挂载到根容器上
export const useTtsStore = defineStore("ttsStore", {
  // 定义state，用来存储状态的
  state: () => {
    return {
      bgVideo: <any>[],
      fileList: <any>[],
      formConfig: store.get("FormConfig.默认"),
      page: {
        asideIndex: "1",
        tabIndex: "1",
      },
      tableData: <any>[], // 文件列表的数据
      currConfigName: "默认", // 当前配置的名字
      config: {
        formConfigJson: store.get("FormConfig"),
        formConfigList: <any>[],
        configLable: <any>[],
        savePath: store.get("savePath"),
      },
      isLoading: false,
      currMp3Buffer: Buffer.alloc(0),
    };
  },
  // 定义getters，类似于computed，具有缓存g功能
  getters: {},
  // 定义actions，类似于methods，用来修改state，做一些业务逻辑
  actions: {
    setDoneStatus(filePath: string) {
      for (const item of this.tableData) {
        if (item.filePath == filePath) {
          item.status = "done";
          return;
        }
      }
    },
    setSavePath() {
      store.set("savePath", this.config.savePath);
    },
    addFormConfig() {
      this.config.formConfigJson[this.currConfigName] = this.formConfig;
      this.genFormConfig();
    },
    genFormConfig() {
      // store.set("FormConfig", this.config.formConfigJson);
      this.config.formConfigList = Object.keys(this.config.formConfigJson).map(
        (item) => ({
          tagName: item,
          content: this.config.formConfigJson[item],
        })
      );
      this.config.configLable = Object.keys(this.config.formConfigJson).map(
        (item) => ({
          value: item,
          label: item,
        })
      );
    },
    async start() {
      this.fileList.map((item: any,index: number) => {
        item.id = index + 1
      })
      
      let ffmpegPath = `${path.join(process.cwd(), "/public/ffmpeg.exe")}`
      let base = `${this.formConfig.baseVideoPath}`

      /* 总的输入图片处理,开头需输入模板视频 */
      let imgAllInput = `-y -i ${base}`
      for(let i = 0; i < this.fileList.length; i++) {
        imgAllInput = imgAllInput + ` -i ${this.fileList[i].raw.path}`
      }

      /* 处理输入图片的尺寸，按基础视频的宽高缩放 */
      let resolutionW = this.formConfig.videoFblSelect.split('*')[0]
      let resolutionH = this.formConfig.videoFblSelect.split('*')[1]
      let videobase = `[0:v]scale=w=${resolutionW}:h=${resolutionH}[videobase];`
      let inputBase = `scale=w='iw*min(${resolutionW}/iw,${resolutionH}/ih)':h='ih*min(${resolutionW}/iw,${resolutionH}/ih)'`

      /* 总的图片输入后宽高调整 */
      let imgAllRecover = ``
      for(let i = 0; i < this.fileList.length; i++) {
        imgAllRecover = imgAllRecover + `[${this.fileList[i].id}:v]${inputBase}[img${this.fileList[i].id}];`
      }

      /* 每一张图的动画 */
      /* 时间间隔处理,默认上面是3.75 */
      let time = this.formConfig.time

      /* 处理总的动画效果 */
      let animateAll: any = ``
      for(let i = 0; i < this.fileList.length; i++) {
        if( i == 0) {
          animateAll = this.animateStrFirst(i,time)
        }else if( i > 0 && i < this.fileList.length-1) {
          animateAll = animateAll + this.animateStr(i,time)
        }
        else {
          animateAll = animateAll + this.animateStrLast(i,time)
        }
      }

      /* 输出配置及存储路径及文件名 */
      let outSet = `-b:v 2048k -aspect 16:9`
      const savePath = path.join(this.config.savePath, this.formConfig.videoName + ".mp4");

      let str = `${ffmpegPath} ${imgAllInput} -filter_complex "${videobase}${imgAllRecover}${animateAll}" ${outSet} ${savePath}`

      let fpchild = exec(
        str,
        {
          encoding: "utf8",
          cwd: process.cwd(),
        },
        async (err:any, stdout:any, stderr:any) => {
          if (err) {
            console.error(err);
            return;
          } else {

          }
        }
      ).on('exit', (code:any) => {
        this.isLoading = false
        console.log('子进程已退出, 退出码 ' + code);
      });
      fpchild.stdout.on('end', (code:any) => {
        this.isLoading = false
        console.log(`视频合成成功。文件路径${savePath}`)
      })
    },

    /* 处理每一个图片的动画 */
    /* i => 第几个 ,time => 间隔时间 */
    animateStr(i:any,time:any) {
      let random = Math.round(Math.random()) == 1 ? 'LB' : 'LT'
      if(random == 'LB') {
        return `[a${i-1}][img${this.fileList[i].id}]overlay='if(gte(t, ${time*i}), min(-overlay_w+(t-${time*i})*${this.formConfig.speed},main_w/2-overlay_w/2),NAN)':'if(gte(t, ${time*(i+1)}), min(main_h/2-overlay_h/2+(t-${time*(i+1)})*${this.formConfig.speed},main_h), main_h/2-overlay_h/2)'[a${i}];`
      }
      if(random == 'LT') {
        return `[a${i-1}][img${this.fileList[i].id}]overlay='if(gte(t, ${time*i}), min(-overlay_w+(t-${time*i})*${this.formConfig.speed},main_w/2-overlay_w/2),NAN)':'if(gte(t, ${time*(i+1)}), min(main_h/2-overlay_h/2-(t-${time*(i+1)})*${this.formConfig.speed},main_h), main_h/2-overlay_h/2)'[a${i}];`
      }
    },

    animateStrFirst(i:any,time:any) {
      let random = Math.round(Math.random()) == 1 ? 'LB' : 'LT'
      if(random == 'LB') {
        return `[videobase][img${this.fileList[i].id}]overlay='main_w/2-overlay_w/2':'if(gte(t, ${time}), min(main_h/2-overlay_h/2+(t-${time})*${this.formConfig.speed},main_h), main_h/2-overlay_h/2)'[a${i}];`
      }
      if(random == 'LT') {
        return `[videobase][img${this.fileList[i].id}]overlay='main_w/2-overlay_w/2':'if(gte(t, ${time}), min(main_h/2-overlay_h/2-(t-${time})*${this.formConfig.speed},main_h), main_h/2-overlay_h/2)'[a${i}];`
      }
    },
    animateStrLast(i:any,time:any) {
      let random = Math.round(Math.random()) == 1 ? 'LB' : 'LT'
      if(random == 'LB') {
        return `[a${i-1}][img${this.fileList[i].id}]overlay='if(gte(t, ${time*i}), min(-overlay_w+(t-${time*i})*${this.formConfig.speed},main_w/2-overlay_w/2),NAN)':'if(gte(t, ${time*(i+1)}), min(main_h/2-overlay_h/2+(t-${time*(i+1)})*${this.formConfig.speed},main_h), main_h/2-overlay_h/2)'`
      }
      if(random == 'LT') {
        return `[a${i-1}][img${this.fileList[i].id}]overlay='if(gte(t, ${time*i}), min(-overlay_w+(t-${time*i})*${this.formConfig.speed},main_w/2-overlay_w/2),NAN)':'if(gte(t, ${time*(i+1)}), min(main_h/2-overlay_h/2-(t-${time*(i+1)})*${this.formConfig.speed},main_h), main_h/2-overlay_h/2)'`
      }
    },
    showItemInFolder(filePath: string) {
      ipcRenderer.send("showItemInFolder", filePath);
    },
  },
});
